package com.ziji.rocketmq.batch;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @author <a href="mailto:ziji.zhao@aliyun.com">ziji</a>
 * @since 2021/11/12
 */
public class BatchConsumer {
    public static void main(String[] args) throws MQClientException {
        // 定义一个 Pull 消费者, 参数为 Consumer Group 名称
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("cg");
        // 指定 Name Server
        consumer.setNamesrvAddr("localhost:9876");
        // 指定从第一条消息开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        // 指定消费 topic 和 tag
        consumer.subscribe("batchTopic", "*");
        // 指定每次可以消费10条消息，默认为 1
        consumer.setConsumeMessageBatchMaxSize(10);
        // 指定每次可以从 broker 拉取 40 条消息，默认为 32
        consumer.setPullBatchSize(40);

        // 注册消息监听
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            // 一旦 broker 中有了其订阅的消息就会触发该方法的执行
            // 其返回值是当前 consumer 消费的状态
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    System.out.println(msg);
                }

                // 消费成功时返回的结果
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                // 消费异常时返回的结果
//                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        consumer.start();
        System.out.println("Consumer Started!");
    }
}




















